#coding=utf-8
import pywifi
from pywifi import const
import time

"""Constants used in pywifi library define here."""

# Define interface status.
IFACE_DISCONNECTED = 0
IFACE_SCANNING = 1
IFACE_INACTIVE = 2
IFACE_CONNECTING = 3
IFACE_CONNECTED = 4

# Define auth algorithms.
AUTH_ALG_OPEN = 0
AUTH_ALG_SHARED = 1

# Define auth key mgmt types.
AKM_TYPE_NONE = 0
AKM_TYPE_WPA = 1
AKM_TYPE_WPAPSK = 2
AKM_TYPE_WPA2 = 3
AKM_TYPE_WPA2PSK = 4
AKM_TYPE_UNKNOWN = 5

# Define ciphers.
CIPHER_TYPE_NONE = 0
CIPHER_TYPE_WEP = 1
CIPHER_TYPE_TKIP = 2
CIPHER_TYPE_CCMP = 3
CIPHER_TYPE_UNKNOWN = 4

KEY_TYPE_NETWORKKEY = 0
KEY_TYPE_PASSPHRASE = 1

status_dict = [
    IFACE_INACTIVE,
    IFACE_CONNECTED,
    IFACE_CONNECTED,
    IFACE_DISCONNECTED,
    IFACE_DISCONNECTED,
    IFACE_CONNECTING,
    IFACE_CONNECTING,
    IFACE_CONNECTING
]

auth_value_to_str_dict = {
    AUTH_ALG_OPEN: 'open',
    AUTH_ALG_SHARED: 'shared'
}

auth_str_to_value_dict = {
    'open': AUTH_ALG_OPEN,
    'shared': AUTH_ALG_SHARED
}

akm_str_to_value_dict = {
    'NONE': AKM_TYPE_NONE,
    'WPA': AKM_TYPE_WPA,
    'WPAPSK': AKM_TYPE_WPAPSK,
    'WPA2': AKM_TYPE_WPA2,
    'WPA2PSK': AKM_TYPE_WPA2PSK,
    'OTHER': AKM_TYPE_UNKNOWN
}

akm_value_to_str_dict = {
    AKM_TYPE_NONE: 'NONE',
    AKM_TYPE_WPA: 'WPA',
    AKM_TYPE_WPAPSK: 'WPAPSK',
    AKM_TYPE_WPA2: 'WPA2',
    AKM_TYPE_WPA2PSK: 'WPA2PSK',
    AKM_TYPE_UNKNOWN: 'OTHER'
}

cipher_str_to_value_dict = {
    'NONE': CIPHER_TYPE_NONE,
    'WEP': CIPHER_TYPE_WEP,
    'TKIP': CIPHER_TYPE_TKIP,
    'AES': CIPHER_TYPE_CCMP,
    'OTHER': CIPHER_TYPE_UNKNOWN
}

cipher_value_to_str_dict = {
    CIPHER_TYPE_NONE: 'NONE',
    CIPHER_TYPE_WEP: 'WEP',
    CIPHER_TYPE_TKIP: 'TKIP',
    CIPHER_TYPE_CCMP: 'AES',
    CIPHER_TYPE_UNKNOWN: 'UNKNOWN'
}


white_list_1118={
    "ssid":"1118",
    "maxSignal":{"position1":-45,"position2":-30},
    "minSignal":{"position1":-65,"position2":-45},
    "authtype":["WPAPSK","WPA2PSK"],
    "akm":[akm_str_to_value_dict["WPAPSK"],akm_str_to_value_dict["WPA2PSK"]],
    "frequency":"Mhz",
    "bssid":"a8:15:4d:e2:b6:a8"
}
white_list_TY6={
    "ssid":"TY6",
    "maxSignal":{"position1":-60,"position2":-30},
    "minSignal":{"position1":-90,"position2":-45},
    "authtype":["WPAPSK","WPA2PSK"],
    "akm":[akm_str_to_value_dict["WPAPSK"],akm_str_to_value_dict["WPA2PSK"]],
    "frequency":"Mhz",
    "bssid":"a8:15:4d:e2:b6:a8"
}

white_list=[white_list_TY6]

def getAverageSignal():
    return

def findFakeAPBySingnal ():
    wifi = pywifi.PyWiFi()
    iface = wifi.interfaces()[0]
    fakeAPList = []

    iface.scan()

    bsses = iface.scan_results()

    for ap in bsses:
        for p in white_list:
            # 如果当前检测的接入点的SSID，MAC在白名单里，用信号结合认证方式检测是否是真实接入点
            if ap.ssid == p["ssid"]:
                if not ap.akm == p["akm"]:
                    temp={"ap":ap,"reason":"auth error"}
                    fakeAPList.append(temp)
                    continue
                if not (ap.signal >= p["minSignal"]["position1"] and ap.signal <= p["maxSignal"]["position1"]):
                    temp = {"ap": ap, "reason": "signal error"}
                    fakeAPList.append(temp)
    return fakeAPList

if __name__=="__main__":
    while(True):
        print('--------------------------------')
        fakeAPList=findFakeAPBySingnal()
        if(len(fakeAPList)==0):
            print('No FakeAP Found!')
        for fake in fakeAPList:
            length = len(fake["ap"].akm)
            authtype = []
            if (length == 0):
                authtype.append("OPEN")
            else:
                for i in fake["ap"].akm:
                    authtype.append(akm_value_to_str_dict[i])
            print("[+]Fake AP Found!","SSID is ",fake["ap"].ssid,",BSSID is ",fake["ap"].bssid,",authtype is",authtype,",Signal is ",fake["ap"].signal,"dBm",fake["reason"])

        time.sleep(8)

    # wifi = pywifi.PyWiFi()
    # iface = wifi.interfaces()[0]
    # fakeAPList = []


    # while(True):
    #     iface.scan()
    #
    #     bsses = iface.scan_results()
    #     for i in bsses:
    #         if i.ssid=='1118':
    #             print('-------------------------------------------')
    #             print("ssid:", i.ssid)
    #             print("bssid:", i.bssid)
    #             # 信号强度
    #             print("signal:", i.signal, "dBm")
    #             # 所在信道
    #             print("frequency:", i.freq, "MHz")
    #             # 认证方式
    #             # 0：NONE 1：WPA 2：WPAPSK 3：WPA2 4：WPA2PSK 5：UNKNOWN
    #             length = len(i.akm)
    #             authtype = []
    #             if (length == 0):
    #                 authtype.append("OPEN")
    #             else:
    #                 for i in i.akm:
    #                     authtype.append(akm_value_to_str_dict[i])
    #             print("auth key mgmt types:", authtype)
    #
    #     time.sleep(10)

